package com.hmdp.interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/*
* token刷新拦截器(只做放行，不做拦截)
* */
public class RefleshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RefleshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        //获取session
//        //HttpSession session = request.getSession();
//
//        //获取到session里的用户信息
//        Object user = session.getAttribute("user");
//
//        //判断用户是否为空
//        if (user == null) {
//            //为空则拦截
//            response.setStatus(401);
//            return false;
//        }
//
//        //不为空将用户信息放到ThreadLocal里
//        UserHolder.saveUser((UserDTO) user);
//
//        //放行
//        return true;
        //1.获取请求头里的token
        String token = request.getHeader("authorization");//authorization请求头
        if(token == null){
            return true;
        }
        //2.根据token获取redis中的用户信息
        String tokenKey = RedisConstants.LOGIN_USER_KEY + token;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(tokenKey);

        if(userMap.isEmpty()){
            return true;
        }

        //4.将token的hash结构转化为UserDTO对象
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);

        //5.存在，保存用户信息到ThreadLocal中
        UserHolder.saveUser(userDTO);
        //6.刷新token有效期
//        stringRedisTemplate.expire(tokenKey, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        stringRedisTemplate.expire(tokenKey,3000, TimeUnit.MINUTES);
        //7.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除用户信息
        UserHolder.removeUser();
    }
}
